package com.bristua.barcode.supplier.biz;

import com.bristua.barcode.common.constants.Constants;
import com.bristua.barcode.common.exception.BizException;
import com.bristua.barcode.common.util.SequenceUtil;
import com.bristua.barcode.supplier.dao.TChannelRequestConfigMapper;
import com.bristua.barcode.supplier.dao.TQrCodeCookieMapper;
import com.bristua.barcode.supplier.enums.SupplierCode;
import com.bristua.barcode.supplier.model.TChannelRequestConfig;
import com.bristua.barcode.supplier.model.TQrCodeCookie;
import com.bristua.barcode.supplier.model.condition.TChannelRequestConfigExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2019/9/5.
 */
@Service
@Transactional
public class AddQrCodeCookieBiz {

    @Resource
    private TQrCodeCookieMapper tQrCodeCookieMapper;

    @Resource
    private TChannelRequestConfigMapper tChannelRequestConfigMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public void addQrCodeCookie(TQrCodeCookie tQrCodeCookie) {
        String id = SequenceUtil.nextId();
        tQrCodeCookie.setCookieId(id);
        tQrCodeCookieMapper.insert(tQrCodeCookie);

        TChannelRequestConfigExample tChannelRequestConfigExample = new TChannelRequestConfigExample();
        tChannelRequestConfigExample.createCriteria().andChannelIdEqualTo(tQrCodeCookie.getChannelId());
        List<TChannelRequestConfig> tChannelRequestConfigs = tChannelRequestConfigMapper.selectByExample(tChannelRequestConfigExample);
        if(tChannelRequestConfigs!=null && tChannelRequestConfigs.size()>0){
            TChannelRequestConfig tChannelRequestConfig = tChannelRequestConfigs.get(0);
            httpRequest(tChannelRequestConfig.getUrl(), tChannelRequestConfig.getParams(),tQrCodeCookie.getContent(), tChannelRequestConfig);
            redisTemplate.opsForValue().set(Constants.COOKIE_KEY+id,id,1L, TimeUnit.MINUTES);
        }

    }

    public static String httpRequest(String strUrl, String param, String cookie,TChannelRequestConfig tChannelRequestConfig) {
//			String params=JSONObject.fromObject(param).toString();
        String result = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(tChannelRequestConfig.getRequestMethod());
            connection.setConnectTimeout(1000);
            connection.setReadTimeout(50000);
            connection.setRequestProperty("Accept", tChannelRequestConfig.getAccept());
            connection.setRequestProperty("Accept-Encoding", tChannelRequestConfig.getAcceptEncoding());
            connection.setRequestProperty("Accept-Language", tChannelRequestConfig.getAcceptLanguage());
            connection.setRequestProperty("User-Agent", tChannelRequestConfig.getUserAgent());
            connection.setRequestProperty("X-Requested-With", tChannelRequestConfig.getxRequestedWith());
            connection.setRequestProperty("Content-Type", tChannelRequestConfig.getContentType());
            connection.setRequestProperty("Referer", tChannelRequestConfig.getReferer());
            connection.setRequestProperty("Origin", tChannelRequestConfig.getOrigin());
            connection.setRequestProperty("Connection", tChannelRequestConfig.getConnection());
            connection.setRequestProperty("Host", tChannelRequestConfig.getHost());

            connection.setRequestProperty("Cookie", cookie);

            if (param != null) {
                byte[] writebytes = param.getBytes();
                // 设置文件长度
                connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream out = connection.getOutputStream();
                out.write(param.getBytes());
                out.flush();
                out.close();
            }

            if (connection.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                result = reader.readLine();
            }
        } catch (IOException e) {
            throw new BizException(SupplierCode.THIRD_CONNECTION_FAIL.getCode(), SupplierCode.THIRD_CONNECTION_FAIL.getMsg());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

}
